<template lang="">
  <div>
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <div class="el-upload__text">
        <img v-if="value !== ''" :src="value" alt="">
        <span v-else>上传图片</span>
      </div>
    </el-upload>
    <div class="iconBox">
      <svg-icon class="iconClass" icon-class="close" @click.native="hIcon" />
    </div>
  </div>
</template>
<script>
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDpSyFFzSfbGemfJfmdDWYR5SXMvFI4Zmi', // 身份识别ID
  SecretKey: 'h8IZZIkunQnshEUTDjyxf7KGwLTLwGJ5' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    hIcon() {
      this.$emit('input', '')
    },
    upload(res) {
      if (res.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'yz98-1307943143', /* 存储桶 */
          Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file // 上传文件对象
        }, (err, data) => {
          console.log(err || data)
          if (data.statusCode === 200) {
            this.$emit('input', `https:${data.Location}`)
            this.$message.success('上传图片成功')
          }
        })
      }
    }
  }
}
</script>
<style scoped>
::v-deep .el-upload-dragger {
  line-height: 56px;
  width: 90px;
  height: 56px;
  margin: 10px 4px;
}
img {
  display: block;
  width: 88px;
  height: 54px;
}
.upload-demo {
  display: flex;
  align-items: center;
}
.el-upload__text {
    position: relative;
}
.iconClass {
    position: absolute;
    font-size: 20px;
    top: -76px;
    right: -6px;
    cursor: pointer;
}
::v-deep .el-upload-dragger {
    overflow: visible;
}
.iconBox {
  position: relative;
  background-color: pink;
}
</style>
